class Node {
    constructor(element, next) {
        this.element = element 
        this.next = next ? next : null 
    }
}

class linkedList {
    constructor() {
        this.length = 0 
        this.head = null 
    }
    append(element) {
        const node = new Node(element) 
        console.log(node);
        let current = this.head
        while (current && current.next) {
            current = current.next
        }
        current ? current.next = node : this.head = node 
        this.length++
    }
    toString() {
        let str = "" 
        let current = this.head
        let decareNum = this.length
        while (decareNum) {
            str += "->" + current.element
            current = current.next
            decareNum--
        }
        return str.slice(2)
    }
    insert(index, element) {
        if (index >= 0 && index <= this.length) {
            const node = new Node(element)
            let current = this.head 
            if (index === 0) {
                node.next = current
                this.head = node 
            } else {
                while (index > 1) {
                    current = current.next 
                    index--
                }
                node.next = current.next
                current.next = node 
            }
            this.length++
        }
        return false
    }
    removeAt(index) {
        if (index >= 0 && index < this.length) {
            let current = this.head 
            if (index === 0) {
                this.head = current.next 
                return current.element
            } else {
                // 试试前后指针
                while (index > 1) {
                    current = current.next 
                    index-- 
                }
            }
            const rtn = current.next.element
            current.next = current.next.next
            this.length--
            return rtn
        }
        return false
    }
    indexOf(element) {
        let current = this.head 
        let index = 0 
        // while (current && current.next) {
        //     if (current.element === element) return index 
        //     current = current.next 
        //     index++
        // }
        // return current.element === element ? index : -1

        /*
            coderwhy 写法 
        */
        while (current) {
            if (current.element === element) {
                return index
            }
            index++ 
            current = current.next 
        }
        return -1
    }
    remove(element) {
        let index = this.indexOf(element)
        return this.removeAt(index)
        
    }
    isEmpty() {
        return this.length === 0 
    }
    getFirst() {
        return this.head.element
    }
}

export {
    linkedList,
    Node
}